﻿using System;
using System.Collections.Specialized;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace BoldBrick.SharePoint.CommonControls.Emails
{
	/// <summary>
	/// Class for sending email from SharePoint server
	/// </summary>
	public class SPEmailMessage
	{
		/// <summary>
		/// Email addresses TO
		/// </summary>
		public string EmailTo { get; set; }
		
		/// <summary>
		/// Email addresses CC
		/// </summary>
		public string EmailCC { get; set; }
		
		/// <summary>
		/// Email addresses BCC
		/// </summary>
		public string EmailBCC { get; set; }
		
		/// <summary>
		/// Email address FROM
		/// </summary>
		public string EmailFrom { get; set; }
		
		/// <summary>
		/// Subject of the email message
		/// </summary>
		public string Subject { get; set; }
		
		/// <summary>
		/// Body of the email message
		/// </summary>
		public string Body { get; set; }
		

		public SPEmailMessage(string emailTo)
		{
			this.EmailTo = emailTo;
		}
		
		/// <summary>
		/// Sends email
		/// </summary>
		/// <param name="web">Content web</param>
		public void Send(SPWeb web)
		{
			StringDictionary headers = GetMessageHeaders();
			SPUtility.SendEmail(web, headers, this.Body);
		}

		/// <summary>
		/// Constructs email message headers
		/// </summary>
		/// <returns>Returns email message headers</returns>
		private StringDictionary GetMessageHeaders()
		{
			if (string.IsNullOrEmpty(this.EmailTo))
			{
				throw new ArgumentNullException("EmailTo", "EmailTo has to be filled.");
			}
			
			StringDictionary headers = new StringDictionary();
			headers.Add("to", this.EmailTo);
			
			if (!string.IsNullOrEmpty(this.EmailCC))
				headers.Add("cc", this.EmailCC);

			if (!string.IsNullOrEmpty(this.EmailBCC))
				headers.Add("bcc", this.EmailBCC);
			
			if (!string.IsNullOrEmpty(this.EmailFrom))
				headers.Add("from", this.EmailFrom);
			
			if (!string.IsNullOrEmpty(this.Subject))
				headers.Add("subject", this.Subject);
			
			headers.Add("content-type", "text/html");

			return headers;
		}
	}
}
